<?php
namespace app\user\controller;
use think\Db;
use Memcached;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\MemcachedCache;
use EasyWeChat\Payment\Order;
/**
 *客户端小程序接口
 *
 */
class Wechat
{

    /**
     *发起支付
     *
     */
    private function initialize($oid,$notify_url)
    {
        $smallapp = Db::name('smallapp') ->where('oid',$oid)->find();
        $mch = Db::name('wechatpay') ->where('oid',$oid)->find();
        $smallapp['appid'] = 'wx88074feb7cdc9318';
        //判断是否为子商户
        if($mch['submerchant']==1){
            $options = [
                'app_id' => config('wechat.APPID'),
                //'app_id' => $smallapp['appid'],
                //'secret'  =>config('wechat.APPSECRET'),
                'payment' => [
                    'merchant_id'        => config('wechat.MCHID'),
                    'key'                => config('wechat.KEY'),
                    'cert_path'          => config('wechat.SSLCERT_PATH'),
                    'key_path'           => config('wechat.SSLKEY_PATH'),
                    'notify_url'         => $notify_url,
                    'sub_app_id'      => $smallapp['appid'],
                    'sub_merchant_id' => $mch['mchid'],
                ],
                'log' => [
                    'level' => 'debug',
                    'file'  => '../log/easywechat.log',
                ],
            ];
            if(config('wechatchche')){
                $memcached = new Memcached();
                $memcached->addServer(config('wechatchche.host'), config('wechatchche.port'));
                $cacheDriver = new MemcachedCache();
                $cacheDriver->setMemcached($memcached);
                $options['cache'] = $cacheDriver;
            }
        }else{
            $options = [
                'app_id' => $smallapp['appid'],
                'payment' => [
                    'merchant_id'        => $mch['mchid'],
                    'key'                => $mch['mchkey'],
                    'cert_path'          => $mch['sslcert_path'],
                    'key_path'           => $mch['sslkey_path'],
                    'notify_url'         => $notify_url,
                ],
                'log' => [
                    'level' => 'debug',
                    'file'  => '../log/easywechat.log',
                ],
            ];
            if(config('wechatchche')){
                $memcached = new Memcached();
                $memcached->addServer(config('wechatchche.host'), config('wechatchche.port'));
                $cacheDriver = new MemcachedCache();
                $cacheDriver->setMemcached($memcached);
                $options['cache']=$cacheDriver;
            }
        }
        $res['app'] = new Application($options);
        $res['submerchant'] = $mch['submerchant'];
        return $res;
    }
    
    
    /**
     * 没有第三方授权获取用户信息
     *
     */
    public function getopenid()
    {
    	$url = 'https://api.weixin.qq.com/sns/jscode2session';
    	$data['appid'] = config('UserWchat.AppID');
    	$data['secret'] = config('UserWchat.AppSecret');
    	$data['js_code'] =input('param.code');//Request::instance()->get('code');
    	$data['grant_type'] ='authorization_code';

    	$userinfo = CURLRequest($url,$data);

        
        if(isset($userinfo['openid'])){
            $res['ukey'] = mwencrypt($userinfo['openid']);
            $res['code'] = 1;
            return $res;
        }else{
            $res['code'] = 0;
            $res['info'] = $userinfo;
            return $res;
        }
    }
    
   
    /**
     *开放平台的授权获取用户
     *
     */
    public function componentgetopenid()
    {
        $oid = input('param.oid');
        $smallapp = Db::name('smallapp') -> where('oid',$oid) -> field('appid')->find();

        $access_token  = controller('cloud/Openplatform');
        $result = $access_token->component_access_token();

        $url = 'https://api.weixin.qq.com/sns/component/jscode2session';
        $data['appid'] = $smallapp['appid'];
        $data['js_code'] =input('param.code');//Request::instance()->get('code');
        $data['grant_type'] ='authorization_code';
        $open_platform = config('wechat.open_platform');
        $data['component_appid'] = $open_platform['app_id'];  //config('wechat.open_platform.app_id');
        $data['component_access_token'] =  $result['component_access_token'];


        $userinfo = CURLRequest($url,$data);
        if(isset($userinfo['openid'])){
            $res['ukey'] = mwencrypt($userinfo['openid']);
            $res['code'] = 1;
            return $res;
        }else{
            $res['code'] = 0;
            $res['info'] = $userinfo;
            return $res;
        }
    }
    
    //小程序内支付
    public function smallapppay($orderinfo){

        $oid = 1;  //运营商ID
        $openid = $orderinfo['openid'];  //openid
        $orderno = $orderinfo['orderno']; //订单号
        $detail = $orderinfo['detail'];  //订单描述
        $price = $orderinfo['price'];  //价格

        //判断是否配置订单号
        if(isset($orderinfo['notify_url'])){
            $notify_url = $orderinfo['notify_url'];
        }else{
            $notify_url = config('website').'/user/Wechat/notify/oid/'.$oid;
        }

        $initialize = $this ->initialize($oid,$notify_url);  //自动执行方法
        $submerchant = $initialize['submerchant']; //是否子商户
        $app = $initialize['app'];
        $payment = $app->payment;
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => $detail,  //订单名称
            'detail'           => $detail,  //订单描述
            'out_trade_no'     => $orderno,  //订单号
            'total_fee'        => (float)$price*100, // 单位：分
        ];

        if($submerchant==1){
            $attributes['sub_openid'] = $openid;
        }else{
            $attributes['openid'] = $openid;
        }
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId); 
            $res['code']= 1 ;
            $res['payment']= json_decode ($json);
            return $res;
        }else{
            $res['code']= 0;
            $res['info']= $result;
            return $res;
        }
    }
    //充值支付结果通知
    public function rechargenotify(){
        $oid = 1;
        $notify_url = config('website').'/user/Wechat/notify/oid/'.$oid;
        $initialize = $this ->initialize($oid,$notify_url);

        $app = $initialize['app'];

        $response = $app->payment->handleNotify(function($notify, $successful){
            //save_log('../log/wxpay',json_encode($notify));
            // 用户是否支付成功
            if ($successful) {
                
                $order_no = $notify['out_trade_no'];
                $data = array(
                    'trade_no' => $notify['transaction_id'], 
                    'pay_status' => 1, 
                    'real_amount' => $notify['total_fee']/100, 
                    'payment_date' => strtotime($notify['time_end']), 
                );
               
                $info = Db::name('rechargeorder')->where('order_no',$order_no)->update($data);
                
                if($info){
                    $this->updatebalance($order_no);
                    return true;
                }else{
                    return false;
                }
            } else { // 用户支付失败
                return false; 
            }
        });
        return $response;

    }
    //更新余额
    private function updatebalance($order_no)
    {
        $order = Db::name('rechargeorder')->where('order_no',$order_no)->find();

        if($order['real_amount']==($order['balance']+$order['deposit'])){
            if($order['balance']>0){
                $balance = Db::name('user')->where('id', $order['uid'])->setInc('balance', $order['balance']);
                if (!$balance) {
                    save_log('../log/user','余额更新出错：'.json_encode($order));
                }
            }
            if($order['deposit']>0){
                $deposit = Db::name('user')->where('id', $order['uid'])->setInc('deposit', $order['deposit']);
                if (!$deposit) {
                    save_log('../log/user','押金更新出错：'.json_encode($order));
                }
            }
        }
    }
    //退款
    public function refund($orderno,$refundno,$total,$refundfel,$oid){

        $notify_url = config('website').'/user/Wechat/notify/oid/'.$oid;

        $initialize = $this ->initialize($oid,$notify_url);

        $submerchant = $initialize['submerchant'];
        $app = $initialize['app'];


        $payment = $app->payment;

        $result = $payment->refund($orderno, $refundno, $total, $refundfel);
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'FAIL') {
            if (isset($result['err_code']) && $result['err_code'] == 'NOTENOUGH') {
                $result = $payment->refund(
                    $orderno,
                    $refundno,
                    $total,
                    $refundfel,
                    null,
                    'out_trade_no',
                    'REFUND_SOURCE_RECHARGE_FUNDS'
                );
            }
        }

        return $result;



    }






}
